<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminController;
use App\Jobs\SetAdminLog;
use App\Models\Setting;
use Carbon\Carbon;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Cache;

class AdminSetController extends AdminController
{
    /**
     * 验证条件数组
     * @var array
     */
    protected $verifyFactor = [
        'name'          =>  'required',
        'key'           =>  'required|alpha_dash|max:50|unique:setting',
        'value'         =>  'required|max:255'
    ];

    public function getIndex()
    {
        $setting = Setting::where('type', 'system')->orderBy('id', 'desc')->paginate(20);
        return view('admin.admin-set')->with(['setting' => $setting]);
    }

    /**
     * 添加设置项
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getAdd()
    {
        return view('admin.admin-set-add');
    }
    public function postAdd(Request $request)
    {
        //整理数据
        $key = $request->input('key');
        //整理数据
        $request->merge([
            'key'       =>  'SET_'.strtoupper($key),
            'type'      =>  'system',
            'isUse'     =>  $request->has('isUse') ? 1 : 0
        ]);
        //验证
        $verifyMsg = $this->verification($request->input());
        if ($verifyMsg)
        {
            $request->merge(['key' => strtoupper($key)]);//还原输入
            return redirect()->action('Admin\AdminSetController@getAdd')->withInput()->withErrors($verifyMsg);
        }

        //Create
        if (Setting::create($request->input()))
        {
            //setLog
            $this->setLog('create', NULL, json_encode($request->except('_token')));
            //清除对应缓存
            Cache::forget(config('cache_name.setting_admin'));
            return ShowMsg('success', getLang('Tips', 'createSuccess'), action('Admin\AdminSetController@getIndex'), 1);
        }

        return ShowMsg('error', getLang('Tips', 'createFail'), action('Admin\AdminSetController@getIndex'), 1);
    }

    /**
     * 修改
     * @param $id
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function getEdit($id)
    {
        //获取设置
        $setting = Setting::find($id);
        if (empty($setting))
            return redirect()->back();
        $setting->key = ltrim($setting->key, 'SET_');
        return view('admin.admin-set-edit')->with(['setting' => $setting]);
    }
    public function postEdit(Request $request, $id)
    {
        //整理数据
        $key = $request->input('key');
        $request->merge([
            'key'       =>  'SET_'.strtoupper($key),
            'isUse'     =>  $request->has('isUse') ? 1 : 0
        ]);
        //验证
        $verifyMsg = $this->verification(
            $request->input(),
            $request->has('key') ? ['key' => 'required|alpha_dash|max:50|unique:setting,key,'.$id] : []
        );
        if ($verifyMsg)
        {
            $request->merge(['key' => strtoupper($key)]);//还原输入
            return redirect()->action('Admin\AdminSetController@getEdit', ['id' => $id])->withErrors($verifyMsg);
        }
        //修改前的值
        $origin = Setting::find($id)->toArray();
        //Update
        if (Setting::where('id', $id)->update($request->except('_token')))
        {
            //setLog
            $this->setLog('update', json_encode($origin), json_encode($request->except('_token')));
            //清除对应缓存
            Cache::forget(config('cache_name.setting_admin'));
            return ShowMsg('success', getLang('Tips', 'updateSuccess'), action('Admin\AdminSetController@getEdit', ['id' => $id]), 1);
        }
        return ShowMsg('error', getLang('Tips', 'updateFail'), action('Admin\AdminSetController@getEdit', ['id' => $id]), 1);
    }

    public function getDel($id)
    {
        //获取设置
        $setting = Setting::find($id);
        //原值
        $origin = $setting->toArray();
        if (!empty($setting))
        {
            if ($setting->isUse === 1)
            {
                return ShowMsg('error', getLang('Tips', 'setUsing'), '', 2);
            }
            if ($setting->delete())
            {
                //setLog
                $this->setLog('delete', json_encode($origin));
                return ShowMsg('success', getLang('Tips', 'deleteSuccess'),'',1);
            }
        }
        return ShowMsg('error', getLang('Tips', 'illegal'),'',1);
    }

    /**
     * 记录日志
     * @param string$type 类型 create update delete
     * @param json null $origin 事件发生前
     * @param json null $ending 事件发生后
     */
    private function setLog($type, $origin = NULL, $ending = NULL)
    {
        switch ($type)
        {
            case 'create':
                $event = [
                    'msg'   =>  'adminSet.create',
                    'type'  =>  'Create'
                ];
                break;
            case 'update':
                $event = [
                    'msg'   =>  'adminSet.update',
                    'type'  =>  'Update'
                ];
                break;
            case 'delete':
                $event = [
                    'msg'   =>  'adminSet.delete',
                    'type'  =>  'Delete'
                ];
                break;
        }
        //push to queue
        $geoIP = geoip()->getLocation();
        $this->dispatch(new SetAdminLog($this->user->id, $geoIP, $event['msg'], Carbon::now(), $event['type'], $origin, $ending));
    }
}
